package com.woniuxy.service.impl;

import com.sun.org.apache.regexp.internal.RE;
import com.woniuxy.dao.OrderMapper;
import com.woniuxy.entity.Order;
import com.woniuxy.entity.Product;
import com.woniuxy.entity.utils.ResponseEntity;
import com.woniuxy.service.OrderService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

//@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Override
    public ResponseEntity generateOrder(Integer pid, Integer num) {

        //使用微服务，获取其他项目的数据
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity productResp = restTemplate.getForObject("http://localhost:8081/product/" + pid, ResponseEntity.class);

        //得到业务代码
        Product product = new Product();

        //处理如果获取不到数据
        if (Integer.parseInt(productResp.get(ResponseEntity.ResponseStatus.CODE.value())+"")== HttpStatus.INTERNAL_SERVER_ERROR.value()){
            return productResp;
        }

        Map map= (Map) productResp.get(ResponseEntity.ResponseStatus.DATA.value());

        //想办法把LinkedHashMap转换为Product对象
        try {
            BeanUtils.populate(product , map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


        Order order = new Order();
        order.setUid(1);
        order.setUsername("tom");
        //查询出来后把数据封装到order
        order.setPid(product.getPid());
        order.setPname(product.getName());
        order.setPrice(product.getPrice());
        //存储购买的数量
        order.setNumber(num);
        Order orderReturn =null;
        //如果订单入库成功，应该扣减库存
        if(product.getStock() - num >= 0){//商品扣减后必须大于等于0才能够扣减商品
            orderReturn =  orderMapper.save(order);
            product.setStock(product.getStock()-num);
            restTemplate.put("http://localhost:8081/product/" ,product);
        }else{
            return new ResponseEntity(HttpStatus.NOT_MODIFIED.value(),"商品卖完了");
        }
        return new ResponseEntity(orderReturn);
    }
}
